<template>
  <router-view :class="[mode]" />
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue';
import dayjs from 'dayjs';
import { useTableRangeCopy } from 'lg.table-copy';
import { useAccountStore, useSettingStore } from '@/store';
import {
  addEventListener,
  copyToClipboard,
  emit,
  loadToken,
  message,
  removeEventListener,
  updateAppStyle,
} from '@/soar';

const store = useSettingStore();

const mode = computed(() => {
  return store.displayMode;
});

function visibilityChange(e: any) {
  switch (e.target.visibilityState) {
    case 'hidden':
      console.debug('隐藏', dayjs().format());
      emit('appVisibility', false);
      break;
    case 'visible':
      console.debug('显示', dayjs().format());
      emit('appVisibility', true);
      loadToken().catch(() => {
        // @ts-ignore
        useAccountStore()?.updateLoginModalVisible(true);
      });
      break;
    default:
      break;
  }
}

onMounted(() => {
  addEventListener(document, 'visibilitychange', visibilityChange);
});

onUnmounted(() => {
  removeEventListener(document, 'visibilitychange', visibilityChange);
});

const DEF = { clientWidth: 0, clientHeight: 0 };
const cache: any = {
  aside: { width: 0, height: 0 },
  header: { width: 0, height: 0 },
  content: { width: 0, height: 0 },
  main: { width: 0, height: 0 },
  tabs: { width: 0, height: 0 },
  breadcrumb: { width: 0, height: 0 },
  footer: { width: 0, height: 0 },
};
setInterval(() => {
  const data: any = {
    aside: document.getElementById('lg-soar-layout-aside') || DEF,
    header: document.getElementById('lg-soar-layout-header') || DEF,
    content: document.getElementById('lg-soar-layout-content') || DEF,
    main: document.getElementById('lg-soar-layout-main') || DEF,
    tabs: document.getElementById('lg-soar-layout-tabs') || DEF,
    breadcrumb: document.getElementById('lg-soar-layout-breadcrumb') || DEF,
    footer: document.getElementById('lg-soar-layout-footer') || DEF,
  };
  const style: any = {};
  for (const k in data) {
    // 宽
    const { clientWidth } = data[k];
    if (cache[k].width !== clientWidth) {
      cache[k].width = clientWidth;
      style[`--app-${k}-width`] = `${clientWidth}px`;
    }
    // 高
    const { clientHeight } = data[k];
    if (cache[k].height !== clientHeight) {
      cache[k].height = clientHeight;
      style[`--app-${k}-height`] = `${clientHeight}px`;
    }
  }

  if (Object.keys(style).length) {
    updateAppStyle(style);
  }
}, 500);

function isMobile() {
  const { userAgent } = navigator;
  const mobileKeywords = ['Mobile', 'Android', 'iPhone', 'iPad', 'Windows Phone'];
  return mobileKeywords.some((keyword) => userAgent.includes(keyword));
}

// 手机端访问自动重定向到手机端地址
if (isMobile() && !location.href.startsWith(`${location.origin}/uniapp`)) {
  message
    .confirm({
      title: '跳转移动端',
      message: '检测到正在使用移动设备访问，是否跳转到移动端？',
      okText: '跳转',
    })
    .then(() => {
      location.href = `${location.origin}/uniapp`;
    });
}

// title提示（会对性能有点影响）
window.addEventListener('mouseover', (e: any) => {
  e = e.target;
  if (e.$$showTitle === undefined) {
    e.$$showTitle = !e.hasAttribute('title');
  }
  if (e.$$showTitle) {
    if (e.innerText === e.innerHTML) {
      e.title = e.innerText;
    } else if (e.tagName === 'INPUT' /* && e.disabled && e.scrollWidth > e.clientWidth */) {
      e.title = e.value;
    } else if (e.classList.contains('lg-description-value')) {
      e.title = e.innerText;
    }
  }
});

// 右键复制
window.addEventListener('contextmenu', (evt: any) => {
  const el = evt.target || {};
  /**
   * 允许复制
   * @param el
   */
  function canCopy(el: any): boolean {
    // 禁用复制优先
    if (el.hasAttribute('disabled-copy')) {
      return false;
    }
    if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
      return true;
    }
    if (el.tagName === 'TD' || el.classList.contains('lg-table-dict') || el.classList.contains('t-table__ellipsis')) {
      return true;
    }
    if (el.classList.contains('lg-description-value')) {
      return true;
    }
    if (el.classList.contains('t-radio__label') || el.classList.contains('t-checkbox__label')) {
      return true;
    }
    // 启用复制兜底
    return el.hasAttribute('enabled-copy');
  }
  // 复制内容
  if (canCopy(el)) {
    evt.preventDefault();
    try {
      copyToClipboard(window.getSelection().toString() || el.value || el.innerText).then(() => {
        message.info('内容已复制');
      });
    } catch (e) {
      console.error(e);
    }
  }
});

function getContent(el: any): string {
  if (el.innerText) {
    return el.innerText;
  }
  if (el.value) {
    return el.value;
  }
  if (el.children?.length) {
    // eslint-disable-next-line no-unreachable-loop
    for (const x of el.children) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      return getContent(x);
    }
  }
}

useTableRangeCopy({
  getContent,
});
</script>
<style lang="less" scoped>
#nprogress .bar {
  background: var(--app-color-primary) !important;
}
</style>
